package com.kingschan.util.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie 操作便捷类
 * @author kingschan
 *2013-4-3
 */
public class CookieUtil {
	private HttpServletRequest request;
	private HttpServletResponse response;
	/**
	 * 得到cookie数组
	 * @return
	 */
	public  Cookie[] getCookies(){
		Cookie[] cs=this.getRequest().getCookies();			
		return cs;
	}
	/**
	 * 传入一个cookie键 删除一个cookie
	 * @param key
	 */
	public  void removeCookie(String key){
		Cookie[] cs=this.getRequest().getCookies();	
		for (Cookie cookie : cs) {
			if (cookie.getName().equals(key)) {
				cookie.setMaxAge(0);
				this.getResponse().addCookie(cookie);
			}
		}
	}
	/**
	 * 传入一个cookie键返回一个cookie对象
	 * @param key
	 * @return
	 */
	public  String getCookieAttribute(String key){
		Cookie[] cs=getCookies();
		String target=null;
		for (Cookie cookie : cs) {
			if (cookie.getName().equals(key)) {
				target=cookie.getValue();
			}
		}
		return target;
	}
	/**
	 * 向客户端添加一个cookie对象
	 * @param name
	 * @param value
	 * @param age
	 */
	public  void setCookieAttribute(String name,String value,int age){
		Cookie c = new  Cookie(name, value);
		c.setMaxAge(age);
		this.getResponse().addCookie(c);
	}
	
	
	

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	
}
